import java.io.*;
import java.net.*;

public class TCPServer {

    public static void main(String[] args) throws IOException {


        // 服务端

        // 1. 创建服务Socket

        // 端口号
        int port = 8888;

        // 创建服务Socket
        ServerSocket serSocket = new ServerSocket(port);
        System.out.println("开启服务器，端口:"+port);

        // 2. 监听端口
        System.out.println("等待客户端连接");
        Socket s = serSocket.accept();


        // 3. 客户端连上后得到的信息
        System.out.println("客户端连上来了");
        System.out.println("客户端的地址"+s.getInetAddress());
        System.out.println("服务器动态端口:"+s.getLocalPort());
        System.out.println("客户端端口:"+s.getPort());


        // 4. 通信
        InputStream in = s.getInputStream();
        OutputStream out = s.getOutputStream();

        // 给客户端发个信息
        out.write("hello!".getBytes());

        // 接收客户端发来的信息
        byte[] buf = new byte[1024];
        int len = in.read(buf);
        String msg = new String(buf,0,len);
        System.out.println("客户端发来:"+msg);


        // 5. 关闭连接
        s.close();
        serSocket.close();



        System.out.println("程序结束");

    }

}